package com.baibei.ebec.user.register;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.basic.module.utils.SMSCountDownTimer;
import com.baibei.basic.module.validator.PhoneValidator;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IPushApi;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.ebec.user.BuildConfig;
import com.baibei.model.UserInfo;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.Empty;
import com.rae.swift.session.SessionManager;

import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Function;

/**
 * 个人注册逻辑
 * Created by ChenRui on 2017/4/28 0028 17:05.
 */
public class RegisterPresenterImpl extends BasicPresenterImpl<RegisterContract.View> implements RegisterContract.Presenter {

    private IPushApi mPushApi;
    private IUserApi mUserApi;

    private RegisterContract.View mRegisterView;
    private final SMSCountDownTimer mSMSCountDownTimer = new SMSCountDownTimer();
    private PhoneValidator mPhoneValidator = new PhoneValidator();

    public RegisterPresenterImpl(Context context, RegisterContract.View view) {
        super(context, view);
        mRegisterView = view;
        mPushApi = ApiFactory.getInstance().getPushApi();
        mUserApi = ApiFactory.getInstance().getUserApi();
    }

    @Override
    public void destroy() {
        mSMSCountDownTimer.finish();
        super.destroy();
    }

    @Override
    public void register() {
        final String mobile = mView.getMobile();
        final String password = mView.getPassword();
        final String smsCode = mRegisterView.getSmsCode();
        final String imei = mView.getImei();
        final String inviteCode = mView.getInviteCode() != null?mView.getInviteCode():"0";

        int type = mView.getType();


        if (TextUtils.isEmpty(password)) {
            mRegisterView.onRegisterFailed("请输入密码");
            return;
        }
        if (TextUtils.isEmpty(mobile)) {
            mRegisterView.onRegisterFailed("请输入手机号码");
            return;
        }
        if (!isMobileNum(mobile)) {
            mView.onRegisterFailed("请输入正确的手机号码");
            return;
        }

        // 个人用户注册
        if (type == IUserApi.TYPE_PERSONAL) {
            performRegister(mobile, password, smsCode,imei,inviteCode);
        }
        // 企业用户，校验验证码
        else if (type == IUserApi.TYPE_ENTERPRISE) {
            createObservable(mPushApi.checkSMSCode(mobile, smsCode)).subscribe(new ApiDefaultObserver<Empty>() {
                @Override
                protected void onError(String s) {
                    mView.onRegisterFailed(s);
                }

                @Override
                protected void accept(Empty empty) {
                    mView.onRegisterSuccess();
                }
            });

        } else {
            mView.onRegisterFailed("未知类型！");
        }
    }

    public boolean isMobileNum(String mobiles) {
        String telRegex = "[1]\\d{10}";
        return TextUtils.isEmpty(mobiles)?false:mobiles.matches(telRegex);
    }

    private void performRegister(final String mobile, final String password, String smsCode,String imei,String inviteCode) {
        Observable<Empty> observable = createObservable(mUserApi.register(mobile, password, mView.getInvitationCode(), smsCode,
                                                        com.baibei.ebec.sdk.BuildConfig.CHANNEL,imei,inviteCode));
        observable.flatMap(new Function<Empty, ObservableSource<UserInfo>>() {
            @Override
            public ObservableSource<UserInfo> apply(@NonNull Empty empty) throws Exception {
                return createObservable(mUserApi.signIn(mobile, password, mView.getInvitationCode(),mView.getImei()));
            }
        }).subscribe(new ApiDefaultObserver<UserInfo>() {
            @Override
            protected void onError(String s) {
                mView.onRegisterFailed(s);
            }

            @Override
            protected void accept(UserInfo userInfo) {
                SessionManager.getDefault().setUser(userInfo);
                mView.onRegisterSuccess();
            }
        });
    }

    @Override
    public void sendSMS() {
        final String mobile = mView.getMobile();
        if (TextUtils.isEmpty(mobile)) {
            mRegisterView.onSmsFailed("请输入手机号码");
            return;
        }
        if (!isMobileNum(mobile)) {
            mView.onSmsFailed("请输入正确的手机号码");
            return;
        }

        mSMSCountDownTimer.start(mRegisterView);

        createObservable(mPushApi.sendSMS(IPushApi.SMS_TYPE_REGISTER, mobile, BuildConfig.INVITEDCODE)).subscribe(new ApiDefaultObserver<Empty>() {
            @Override
            protected void onError(String s) {
                mSMSCountDownTimer.finish();
                mSMSCountDownTimer.onFinish();
                mView.onSmsFailed(s);
            }

            @Override
            protected void accept(Empty empty) {
                mView.onSmsSuccess();
            }
        });

    }

    @Override
    public boolean isInCountdown() {
        return !mSMSCountDownTimer.isFinish();
    }

    @Override
    public void cancel() {
        cancelRequest();
    }
}
